import React from 'react'


import {Dimensions, Image, StyleSheet, Text, TextInput, View, TouchableOpacity, AsyncStorage} from 'react-native';
import BasePage from './Component/Common/BasePage';
import PageView from './Component/Common/PageView'
import {Button} from 'teaset';
import CommonStyle from "./Component/CommonStyle";

import RegisterPage from './RegisterPage'

let screenW = Dimensions.get('window').width;
let screenH = Dimensions.get('window').height;


import Start from './MainScreen'
import FindPasswordPage from './FindPasswordPage'
import SQLite from './SQLite';
import GetData from "./GetData";

import Storage from 'react-native-storage';


let storage = new Storage({
    //最大容量，默认值1000条数据循环存储
    size: 1000,

    //存储引擎：RN使用AsyncStorage
    //如果不指定则数据只会保存在内存中，重启后即丢失
    storageBackend: AsyncStorage,

    //数据过期时间，默认一整天（1000 * 3600 * 24 毫秒），设为null则永不过期
    defaultExpires: null,

    //读写时在内存中缓存数据，默认开启
    enableCache: true,

    // 如果storage中没有相应数据，或数据已过期，
    // 则会调用相应的sync方法，无缝返回最新数据。
    // sync方法的具体说明会在后文提到
    // 你可以在构造函数这里就写好sync的方法
    // 或是写到另一个文件里，这里require引入

});
exports.storage = storage;

storage.sync = require('./RNAsyncStorage_asyn').ssss;

var sqLite = new SQLite();
var db;


export default class LoginPage extends BasePage {

    _onPress: (buttonIndex: number) => void;


    constructor(props) {

        super(props);

        this._onChangeText = this._onChangeText.bind(this);
        this._onChangeTexttwo = this._onChangeTexttwo.bind(this);

        this.state = {
            ...this.state,
            name: '',
            password: '',
            isture: false,
            inputText: '',
            passwordis: true,
            isload: 0
        };

    }

    compennetDidUnmount() {
        sqLite.close();
    }

    componentWillMount() {



        //开启数据库
        if (!db) {
            db = sqLite.open();
        } else {
            //建表
            sqLite.createTable();
        }

        AsyncStorage.getItem('person', (error, result) => {
            if (error) {
                // alert('读取失败')
            } else {
                console.log(result)
                let jsonValue = JSON.parse(result);

                var isloadjs = jsonValue ? jsonValue.islond : 0;

                if (isloadjs == 1) {

                    this.navigator.resetTo({
                        view: <Start/>
                    })

                }

            }
        })
        // //模拟一条数据
        var userData = [];
        var user = {};
        user.name = "18355160399";
        user.age = "28";
        user.sex = "男";
        user.password = "123456";
        user.headurl = "";
        user.qq = "111222";
        userData.push(user);
        // //插入数据
        sqLite.insertUserData(userData);
        //
        // var userData2 = [];
        // var user2 = {};
        // user2.name = "18355160399";
        // user2.age = "22";
        // user2.sex = "女";
        // user2.password = "125533";
        // user2.headurl = "";
        // user2.qq = "43231423";
        // userData2.push(user2);
        // // //插入数据
        // sqLite.insertUserData(userData2);
        //
        // var userData3 = [];
        // var user3 = {};
        // user3.name = "18355559399";
        // user3.age = "22";
        // user3.sex = "女";
        // user3.password = "123456";
        // user3.headurl = "";
        // user3.qq = "43231423";
        // userData3.push(user3);
        // // //插入数据
        // sqLite.insertUserData(userData3);

        //
        //
        // var userData3 = [];
        // var user3 = {};
        // user3.name = "15156016225";
        // user3.age = "21";
        // user3.sex = "男";
        // user3.password = "312312";
        // user3.headurl = "145223@qq.com";
        // user3.qq = "124324";
        // userData3.push(user3);
        // // //插入数据
        // sqLite.insertUserData(userData3);
        //
        // AsyncStorage.getItem('person', function (error, result) {
        //     if (error) {
        //         // alert('读取失败')
        //     } else {
        //         console.log(result)
        //         let jsonValue = JSON.parse(result);
        //         var name = jsonValue.islond;
        //         if (name == 1) {
        //             this.navigator.push({
        //                 view: <Start/>
        //             })
        //         }


        //     }
        // })


    }

    /**
     * 验证是否为手机号
     * @param {*} str
     */
    isPoneAvailable(str) {
        let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (str.length == 0 || str == null) {
            return false;
        } else if (!myreg.test(str)) {
            return false;
        } else {
            return true;
        }
    }

    _saveData() {
        if (this.state.name == '') {
            alert('请填写手机号')
            return
        }

        if (this.state.password == '') {
            alert('请填写密码')
            return
        }

        //查询
        db.transaction((tx) => {
            tx.executeSql("select * from user  WHERE name=? ", [this.state.name], (tx, results) => {
                var len = results.rows.length;
                if (len == 0) {
                    alert('没有该用户')
                }
                for (let i = 0; i < len; i++) {
                    var u = results.rows.item(i);
                    if (u.name == this.state.name) {

                        if (u.password == this.state.password) {
                            //   保存数据

                            var person = {
                                name: u.name,
                                islond: 1,
                                headurl: u.headurl
                            }
                            var jsonStr = JSON.stringify(person)


                            AsyncStorage.setItem('person', jsonStr, function (error) {
                                if (error) {
                                    // alert('存储失败')
                                } else {
                                    // alert('存储完成')
                                }
                            })


                            this.navigator.resetTo({
                                view: <Start/>
                            })

                        } else {
                            alert('密码错误，请重新输入')
                        }
                    }

                    //一般在数据查出来之后，  可能要 setState操作，重新渲染页面
                }


            });
        }, (error) => {//打印异常信息
            alert('重新打开app')
        });

    };


    _onChangeText(inputData) {

        this.setState({
            name: inputData
        })
    }

    _onChangeTexttwo(inputData) {

        this.setState({
            password: inputData
        })
    }


    renderNavigationBar() {
        return (
            null
        );
    }


    renderPage() {
        return (

            <PageView style={{flex: 1}} hiddenNav={true} fromPage={this} {...this.state}>

                <View style={{
                    flexDirection: 'column',
                    flex: 1
                }}>
                    <View style={{height: 300, width: screenW, justifyContent: 'center', alignItems: 'center'}}>

                        <Text style={{
                            fontSize: 32,
                            color: '#666666'
                        }}>
                            易盈宝典
                        </Text>
                    </View>

                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        height: 40,
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginRight: 15
                    }}>

                        <Image

                            resizeMode={'stretch'} style={{
                            width: 20, height: 20,
                        }}
                            source={require('./images/rentou.png')}/>
                        <TextInput
                            underlineColorAndroid={'#1196DB'}
                            placeholder="请输入用户名"
                            editable={true}//是否可编辑
                            style={styles.inputStyle}//input框的基本样式
                            value={this.state.name}
                            onChangeText={this._onChangeText}//输入框改变触发的函数

                        />
                        <TouchableOpacity
                            style={{

                                position: 'absolute',
                                right: 0,
                            }}

                            onPress={() => {


                                this.setState({name: ''});

                            }}

                            activeOpacity={1} key={0}
                        >


                            <Image

                                resizeMode={'stretch'} style={{
                                width: 30, height: 30,

                            }}
                                source={require('./images/cha_close.png')}/>
                        </TouchableOpacity>

                    </View>
                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        marginTop: 10,
                        height: 40,
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginRight: 15
                    }}>

                        <Image

                            resizeMode={'stretch'} style={{
                            width: 20, height: 20,
                        }}
                            source={require('./images/password.png')}/>
                        <TextInput
                            style={styles.inputStyle}//input框的基本样式
                            underlineColorAndroid={'#1196DB'}
                            placeholder="请输入密码"
                            editable={true}//是否可编辑
                            keyboardType="number-pad"
                            secureTextEntry={this.state.passwordis}
                            onChangeText={this._onChangeTexttwo}//输入框改变触发的函数
                        />


                        <TouchableOpacity
                            style={{

                                position: 'absolute',
                                right: 5,
                            }}

                            onPress={() => {
                                this.setState({passwordis: !this.state.passwordis});

                            }}

                            activeOpacity={1} key={0}
                        >

                            <Image
                                resizeMode={'stretch'} style={{
                                width: 18, height: 15,
                            }}
                                source={require('./images/see.png')}/>
                        </TouchableOpacity>


                    </View>


                    <Button
                        title="登陆"
                        style={{marginLeft: 40, marginRight: 40, marginTop: 40, height: 50}}
                        onPress={() => this._saveData()}
                        color="#1196DB">
                    </Button>
                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        marginTop: 10,
                        height: 40,
                        flexDirection: 'row-reverse',
                        alignItems: 'center',
                        marginRight: 15
                    }}>


                        <TouchableOpacity

                            onPress={() => {

                                this.navigator.push({
                                    view: <FindPasswordPage/>
                                })
                            }}

                            activeOpacity={1} key={0}
                        >
                            <Text style={{
                                color: '#1196DB'
                            }}>忘记密码</Text>
                        </TouchableOpacity>
                        <View
                            style={{
                                backgroundColor: '#f2f',
                                width: 1,
                                marginLeft: 10,
                                marginRight: 10,
                                height: 20
                            }}
                        />
                        <TouchableOpacity
                            style={{}}
                            onPress={() => {

                                this.navigator.push({
                                    view: <RegisterPage/>
                                })
                            }}

                            activeOpacity={1} key={0}
                        >
                            <Text style={{
                                color: '#1196DB',
                            }}>注册</Text>

                        </TouchableOpacity>

                    </View>

                </View>

            </PageView>
        );

    }

    componentDidMount() {

    }


}
const
    styles = StyleSheet.create({

        button2: {
            height: 29,
            width: CommonStyle.screenwidth / 5,
            flexDirection: 'row',
            borderTopRightRadius: 5,
            borderBottomRightRadius: 5,
        }, inputStyle: {

            flex: 1,
            marginLeft: 10,
        }
    });
